package com.infopatent.shldevtools.tools;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import java.beans.PropertyVetoException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import org.apache.log4j.Logger;

/**
 * 用于通过C3P0数据库连接池来获取数据库连接的工具类
 *
 * @author shaohailong
 */
public class C3P0Tools {

    /**
     * 数据库连接池
     */
    private static C3P0Tools dbPool;
    /**
     * 数据源
     */
    private ComboPooledDataSource dataSource;
    /**
     * 获取日志类,这里使用了log4j
     */
    private static Logger log = Logger.getLogger(C3P0Tools.class);

    static {
        dbPool = new C3P0Tools();
    }

    /**
     * 无参构造方法 无需进行调用 该类提供的数据库连接直接通过静态方法 getInstance 和getConnection 就可以得到
     */
    public C3P0Tools() {
        Properties props = new Properties();
        try {
            props.load(this.getClass().getResourceAsStream("/config.properties"));
        } catch (IOException ex) {
            log.error("配置文件信息获取失败", ex);
        }

        try {
            dataSource = new ComboPooledDataSource();
            dataSource.setUser(props.getProperty("db.username"));
            dataSource.setPassword(props.getProperty("db.password"));
            dataSource.setJdbcUrl(props.getProperty("db.url"));
            dataSource.setDriverClass(props.getProperty("db.driver"));
            dataSource.setInitialPoolSize(4);
            dataSource.setMinPoolSize(5);
            dataSource.setMaxPoolSize(20);
            dataSource.setMaxStatements(150);
            dataSource.setMaxIdleTime(1800);
        } catch (PropertyVetoException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取该类的实例,这里使用了单例,通过静态方法直接获得实例
     * @return 该类实例
     */
    public static C3P0Tools getInstance() {
        return dbPool;
    }

    /**
     * 获取数据库连接
     * @return 数据库连接
     */
    public final Connection getConnection() {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException("无法从数据源获取连接 ", e);
        }
    }

    /**
     * 内部测试方法,开发时使用,确保能正确获取数据库连接
     * @param args
     * @throws SQLException 
     */
    public static void main(String[] args) throws SQLException {
        Connection con = null;
        try {
            con = C3P0Tools.getInstance().getConnection();
        } catch (Exception e) {
        } finally {
            if (con != null) {
                con.close();
            }
        }
    }
}